package com.num2.controller.xjg;

import com.num2.form.xjg.LoginForm;
import com.num2.model.xjg.LoginModel;
import com.num2.service.xjg.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class UserCtrl {
    @Resource
    private UserService userService;
    @RequestMapping("/login")
    public String Login(LoginForm loginForm,Model m,HttpSession session,HttpServletResponse resp){
        LoginModel loginModel = userService.login(loginForm);
        if (loginModel != null) {
        	//用户密码
        	session.setAttribute("user_pwd",loginForm.getPassword());
        	//用户名字
        	session.setAttribute("user_name",loginForm.getUsername());
        	//用户ID
        	session.setAttribute("user_id",loginModel.getUser_id());                 
        	
        	
        	//当点击了记住密码选择框
        	if ("yes".equals(loginForm.getRember())) {
                //创建两个Cookie对象 username和password
                Cookie nameCookie = new Cookie("username",loginForm.getUsername());
                //设置Cookie的有效期为3天
                nameCookie.setMaxAge(60 * 60 * 24 * 3);
                Cookie pwdCookie = new Cookie("password",loginForm.getPassword());
                pwdCookie.setMaxAge(60 * 60 * 24 * 3);            
                resp.addCookie(nameCookie);
                resp.addCookie(pwdCookie);                 
        	}
        	
        	//判断验证码是否输入正确。不区分大小写。
        	if(((String) session.getAttribute("code")).equalsIgnoreCase(loginForm.getCode())){       
            	
        		//权限，判断跳转哪个界面. 0代表普通用户，1代表管理员     
            	if(loginModel.getUser_power()==0){  
            		
            		//是否被冻结，0代表正常，1代表冻结
            		if(loginModel.getStatement()==0){
            			return "demo/index";
            		}else{
            			m.addAttribute("statement", "您的账户以被冻结,请联系。。。");
            			return "login";
            			}
            		}else{
            			return "demo/admin";
            		}
            	}else{
            		m.addAttribute("codeinfo", "您输入的验证码错误"); 
            		return "login";
            		}     	     	
        	}
        	else{
        	m.addAttribute("errorinfo", "您输入的用户名或密码错误");
            return "login";   
        }
    }
    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}